//
// SignalHandler.h
//
// $Id: //poco/1.4/Foundation/include/Poco/SignalHandler.h#2 $
//
// Library: Foundation
// Package: Threading
// Module:  SignalHandler
//
// Definition of the SignalHandler class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#ifndef Foundation_SignalHandler_INCLUDED
#define Foundation_SignalHandler_INCLUDED


#include "Poco/Foundation.h"
#include "Poco/Thread.h"

#if defined(POCO_OS_FAMILY_UNIX)


#include <vector>
#include <setjmp.h>
#include <signal.h>

namespace Poco {
/*
 * threads created by main() will inherit a copy of the signal mask.
*/
class SignalBlocker
{
	enum SignalBlockerType
	{
		SignalBlockerType_Thread,
		SignalBlockerType_Proc
	};
public:
	SignalBlocker(SignalBlockerType type = SignalBlockerType_Thread):m_type(type)
	{
		sigemptyset(&m_sset);
	}
	
	~SignalBlocker()
	{
		if (m_type == SignalBlockerType_Thread)
		{
			pthread_sigmask(SIG_BLOCK, &m_oldSset, 0);
		}
		else if(m_type == SignalBlockerType_Proc)
		{
			sigprocmask(SIG_BLOCK, &m_oldSset,0);
		}
	}
	
	void block(unsigned int sig)		/// can call repeatedly
	{
		sigaddset(&m_sset, sig); 
		if (m_type == SignalBlockerType_Thread)
		{
			pthread_sigmask(SIG_BLOCK, &m_sset, &m_oldSset);
		}
		else if(m_type == SignalBlockerType_Proc)
		{
			sigprocmask(SIG_BLOCK, &m_sset, &m_oldSset);
		}
	}
private:
	sigset_t 			m_sset;
	sigset_t 			m_oldSset;
	SignalBlockerType 	m_type;
	friend class ThreadImpl;
	friend class Thread;
};

typedef void (*SignalHandler_SA_Handler)(int sig);
typedef void (*SignalHandler_SA_Sigaction)(int sig, siginfo_t * siginfo, void * arg);

class Foundation_API SignalHandler
	/// This helper class simplifies the handling of POSIX signals.
	///
{
public:
	SignalHandler();
		/// Creates the SignalHandler.

	~SignalHandler();
		/// Destroys the SignalHandler.

	static void install(unsigned int sig,SignalHandler_SA_Handler callback);
		/// add a signal handler
	
	static void install(unsigned int sig,unsigned int flags, SignalHandler_SA_Sigaction callback);
		/// add a signal handler

private:
	friend class ThreadImpl;
	friend class Thread;
};

} // namespace Poco


#endif // POCO_OS_FAMILY_UNIX


#endif // Foundation_SignalHandler_INCLUDED
